package org.example.auth.config.oauth.jdbc;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import org.example.api.system.RemoteOauthClientService;
import org.example.api.system.domain.vo.RemoteOauthClientVo;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.util.StringUtils;

/**
 * Add  <i>archived = 0</i> condition
 *
 */
public class CustomJdbcClientDetailsService implements ClientDetailsService {

    private final RemoteOauthClientService remoteOauthClientService;

    public CustomJdbcClientDetailsService(RemoteOauthClientService remoteOauthClientService) {
        this.remoteOauthClientService=remoteOauthClientService;
    }


    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        RemoteOauthClientVo remoteOauthClientVo= remoteOauthClientService.loadClientByClientId(clientId);
        if(ObjectUtil.isNotNull(remoteOauthClientVo)){
            BaseClientDetails details=new BaseClientDetails(remoteOauthClientVo.getClientId(), remoteOauthClientVo.getResourceIds(),
                    remoteOauthClientVo.getScope(), remoteOauthClientVo.getAuthorizedGrantTypes(), remoteOauthClientVo.getAuthorities(),
                    remoteOauthClientVo.getWebServerRedirectUri());
            details.setClientSecret(remoteOauthClientVo.getClientSecret());
            if(ObjectUtil.isNotNull(remoteOauthClientVo.getAccessTokenValidity())){
                details.setAccessTokenValiditySeconds(remoteOauthClientVo.getAccessTokenValidity());
            }
            if(ObjectUtil.isNotNull(remoteOauthClientVo.getRefreshTokenValidity())){
                details.setRefreshTokenValiditySeconds(remoteOauthClientVo.getRefreshTokenValidity());
            }
            if(ObjectUtil.isNotNull(remoteOauthClientVo.getAdditionalInformation())){
                details.setAdditionalInformation(JSON.parseObject(remoteOauthClientVo.getAdditionalInformation()));
            }
            if(ObjectUtil.isNotNull(remoteOauthClientVo.getAutoapprove())){
                details.setAutoApproveScopes(StringUtils.commaDelimitedListToSet(remoteOauthClientVo.getAutoapprove()));
            }
            return details;
        }
        return null;
    }
}